package com.gem.springbootdemo.control;

import com.gem.springbootdemo.entity.CarGood;
import com.gem.springbootdemo.entity.Goods;
import com.gem.springbootdemo.entity.User;
import com.gem.springbootdemo.service.GoodsService;
import com.gem.springbootdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/user")
@Controller
@SessionAttributes({"user","car"})
public class UserControl {
    @Autowired
    private UserService userService;
    @Autowired
    private GoodsService goodsService;
   //点击登录按钮,跳转的controller
    //通过形参接收请求的参数(请求的参数必须和形参的名字一致)   springMVC 的优化
    //只能post请求访问,get请求无权访问
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(String  password, String username, Model model, String  auto, HttpServletResponse response){  // auto  是否自动登录
       //通过调用serice的登录业务区判断
        User user=userService.Login(username,password);
        if(user!=null){
//            将用户信息放置model域,然后转到session域
            model.addAttribute("user",user);
            //是否自动登录
            if(auto!=null&&auto.equals("auto")){//选择了自动登录按钮
                Cookie cookie1=new Cookie("username",username);
                Cookie cookie2=new Cookie("password",password);
                //保存一天 单位是秒
                cookie1.setPath("/");
                cookie2.setPath("/");
                cookie1.setMaxAge(60*60*24);
                cookie2.setMaxAge(60*60*24);
                response.addCookie(cookie1);
                response.addCookie(cookie2);
            }else{
//               不自动登录,删除cookie
                Cookie cookie1=new Cookie("username",username);
                Cookie cookie2=new Cookie("password",password);
                //保存一天 单位是秒
                cookie1.setPath("/");
                cookie2.setPath("/");
                cookie1.setMaxAge(0);//删除cookie
                cookie2.setMaxAge(0);//删除cookie
                response.addCookie(cookie1);
                response.addCookie(cookie2);
            }
            //首页的control去获得首页的数据 (注意点:如果首页是纯静态 index(前端) ,如果是动态 control(后台))
            return "forward:/goods/index";//转发到control   必须添加/
        }
//        登录失败
        model.addAttribute("error","1");
//        return "login.html" 页面
          return "login";
    }

    @RequestMapping("/register")
    //实体类属性与请求的参数名一致,日期类型必须给转换格式
    public String register(User user,Model model){
     boolean flag=userService.register(user);
     if(flag){
         //注册成功,跳转的login.html页面    return "页面"       return "forward:控制层" 转发         return "redirect:控制层"  重定向
         return "login";
     }
     model.addAttribute("error","1");
     return "register";
    }

    //接口  以后想返回json是什么类型的数据,这里就写什么类型
    @ResponseBody
    @RequestMapping("/isUsernameExist")
    public boolean  isUsernameExist(String username){
      User user =userService.getUserByUsername(username);
      return user==null ?false:true;

    }

    @RequestMapping("/redis")
    public String  redisShow(Model  model) throws IOException {
        List<User> users=userService.getAllUser();
        model.addAttribute("users",users);
        return "index";

    }

    @RequestMapping("/cart")
    public String cart(Model model,int gid, int num, HttpSession session ,HttpServletResponse response){
//      1.从session中获得公务车里面的商品列表   key:car
        Object object=session.getAttribute("car");
       User user= (User) session.getAttribute("user");
        List<CarGood>  goods=null;
        if (object!=null){
//            购物车里面已经有商品  // //专门一个购物车里面商品的实体类
              goods= (List<CarGood>) object;  //购物车里面是商品的列表      //商品的基本信息
            //根据gid号遍历购物车,查看商品是否已经存在,存在直接添加数量,不存在在添加商品
           boolean flage=false;
            for (int i=0;i<goods.size();i++){
                if (goods.get(i).getGoods().getId()==gid){
                    //已经存在   修改数量
                    goods.get(i).setNum(goods.get(i).getNum()+num);
                    flage=true;//商品在购物车中存在
                }
            }
            if(!flage){
            //不存在的情况
          Goods goods1=  goodsService.getGoodsById(gid);
            CarGood new_carGood=new CarGood(goods1,num,user);
            goods.add(new_carGood);
            }
        }else{
            //购物车已空  ,先实例化一个集合
            goods=new ArrayList<CarGood>();
            Goods goods1=  goodsService.getGoodsById(gid);
            CarGood new_carGood=new CarGood(goods1,num,user);
            //往集合里面放商品
            goods.add(new_carGood);
        }
        //放置session   (默认购物车存放时间24小时,浏览器关闭之后还能用  Coookie先持久化)
        Cookie cookie=new Cookie("JSESSIONID",session.getId());
        cookie.setMaxAge(60*60*24);//24小时
        cookie.setPath("/");
        //服务器将Cookie发送给浏览器,然后coookie存储在浏览器上
        response.addCookie(cookie);
        //设置session的时间  session底层依赖cookie这个值 JSESSIONID
        session.setMaxInactiveInterval(60*24);//单位是分钟
        //将购物车放在session中
        model.addAttribute("car",goods);
        return  "redirect:/user/cartToo";//刷新出错,改用重定向
    }
    @RequestMapping("/cartToo")
    public  String carToo(){

        return "cart";
    }
    @RequestMapping("/updateNum")
    public boolean updateNum(int num,int gid,HttpSession session,Model model){
        List<CarGood> list= (List<CarGood>) session.getAttribute("car");
        for (int i=0;i<list.size();i++){
           if (list.get(i).getGoods().getId()==gid) {
               list.get(i).setNum(num);
               model.addAttribute("car",list);
               return true;
           }
        }
        return false;
    }



}
